package com.xinlin.framework.web.service;

import java.util.concurrent.TimeUnit;

import com.xinlin.common.core.domain.entity.AppUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.xinlin.common.constant.CacheConstants;
import com.xinlin.common.core.domain.entity.SysUser;
import com.xinlin.common.core.redis.RedisCache;
import com.xinlin.common.exception.user.UserPasswordNotMatchException;
import com.xinlin.common.exception.user.UserPasswordRetryLimitExceedException;
import com.xinlin.common.utils.SecurityUtils;
import com.xinlin.framework.security.context.AuthenticationContextHolder;

/**
 * 登录密码方法
 *
 * @author xinlin
 */
@Slf4j
@Component
public class SysPasswordService {
    @Autowired
    private RedisCache redisCache;

    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime}")
    private int lockTime;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getSysCacheKey(String username) {
        return CacheConstants.SYS_PWD_ERR_CNT_KEY + username;
    }

    private String getAppCacheKey(String username) {
        return CacheConstants.APP_PWD_ERR_CNT_KEY + username;
    }

    public void validateSysUser(SysUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();
        log.info("pwd {} ,username {} ", password, username);
        Integer retryCount = redisCache.getCacheObject(getSysCacheKey(username));

        if (retryCount == null) {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }
        log.info(" username : {} ,password : {} ", user.getUserName(), user.getPassword());
        if (!matches(user.getPassword(), password)) {
            retryCount = retryCount + 1;
            redisCache.setCacheObject(getSysCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new UserPasswordNotMatchException();
        } else {
            clearSysUserLoginRecordCache(user.getUserName());
        }
    }

    public void validateAppUser(AppUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();
        log.info("pwd {} , username {} ", password, username);
        Integer retryCount = redisCache.getCacheObject(getAppCacheKey(username));

        if (retryCount == null) {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }
        log.info(" username : {} ,password : {} ", username, user.getPassword());
        if (!matches(user.getPassword(), password)) {
            retryCount = retryCount + 1;
            redisCache.setCacheObject(getAppCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new UserPasswordNotMatchException();
        } else {
            clearSysUserLoginRecordCache(user.getUserName());
        }
    }

    public boolean matches(String userPassWord, String rawPassword) {
        return SecurityUtils.matchesPassword(rawPassword, userPassWord);
    }

//    public boolean matches(SysUser user, String rawPassword) {
//        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
//    }

    public void clearSysUserLoginRecordCache(String loginName) {
        if (redisCache.hasKey(getSysCacheKey(loginName))) {
            redisCache.deleteObject(getSysCacheKey(loginName));
        }
    }

    public void clearAppUserLoginRecordCache(String loginName) {
        if (redisCache.hasKey(getAppCacheKey(loginName))) {
            redisCache.deleteObject(getAppCacheKey(loginName));
        }
    }
}
